package top.yuhaitao.core.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import top.yuhaitao.core.pojo.ProductCategory;
import top.yuhaitao.core.pojo.ProductInfo;
import top.yuhaitao.core.service.ProductCategoryService;
import top.yuhaitao.core.service.ProductInfoService;
import top.yuhaitao.core.vo.ProductInfoVO;
import top.yuhaitao.core.vo.ProductVO;
import top.yuhaitao.core.vo.ResultVO;

/**
 * 买家商品
 *
 * @author ht.yu
 */

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    public ResultVO<List<ProductVO>> list() {

        // 1. 查询所有上架的商品
        List<ProductInfo> ProductInfoList = productInfoService.findUpAll();
        // 2. 查询类目（一次性查询）
        List<Integer> categoryTypeListIds = ProductInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        List<ProductCategory> ProductCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeListIds);

        // 3. 数据拼装
        List<ProductVO> productVOList = new ArrayList<ProductVO>();
        for (ProductCategory productCategory : ProductCategoryList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVO> productInfoVOList = new ArrayList<ProductInfoVO>();
            for (ProductInfo productInfo : ProductInfoList) {
                if (productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        ResultVO<List<ProductVO>> resultVO = new ResultVO<List<ProductVO>>();
        resultVO.setCode(0);
        resultVO.setMessage("成功");
        resultVO.setData(productVOList);
        return resultVO;
    }

}
